<template>
  <div class="query">
    <van-nav-bar
        fixed
        class="query-nav-bg"
        :title="$t('query.t1')"
    />
    <van-form @submit="onSubmit" style="margin: 60px 0;">
      <van-cell-group inset>
        <van-field
            v-model="dbName"
            name="dbName"
            :label="$t('query.t2')"
            :placeholder="$t('query.t2')"
            :rules="[{ required: true, message: $t('query.t3') }]"
            @blur="setSession"
            is-link
            readonly
            @click="showPicker = true"
        />
        <van-popup v-model:show="showPicker" round position="bottom">
          <van-picker
              show-toolbar
              :columns="columns"
              @cancel="showPicker = false"
              :default-index="defaultIndex"
              @confirm="onConfirm"
          />
        </van-popup>
        <van-field
            v-model="method"
            name="method"
            :label="$t('query.t4')"
            :placeholder="$t('query.t4')"
            :rules="[{ required: true, message: $t('query.t5') }]"
            @blur="setSession"
        />
        <van-field name="direction" :label="$t('query.t6')" :rules="[{ required: true, message: $t('query.t7') }]">
          <template #input>
            <van-radio-group v-model="direction" direction="horizontal" @change="setSession">
              <van-radio name="1">{{ $t('query.t8') }}</van-radio>
              <van-radio name="2">{{ $t('query.t9') }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-button
            plain
            :type="isFormat.input ? 'info' : 'primary'"
            native-type="button"
            size="mini"
            @click="onFormat(input, 'input')"
            style="float: right">
          {{ isFormat.input ? $t('query.t15') : $t('query.t14') }}
        </van-button>
        <van-field
            v-model="input"
            name="input"
            rows="2"
            autosize
            :label="$t('query.t10')"
            type="textarea"
            :placeholder="$t('query.t10')"
            :rules="[{ required: true, message: $t('query.t11') }]"
            show-word-limit
            @blur="setSession"
            class="query-format"
            :style="{'--formatHeight':  inputFormatHeight}"
        />
        <van-button
            plain
            :type="isFormat.output ? 'info' : 'primary'"
            native-type="button"
            size="mini"
            @click="onFormat(output, 'output')"
            style="float: right">
          {{ isFormat.output ? $t('query.t15') : $t('query.t14') }}
        </van-button>
        <van-field
            v-model="output"
            name="output"
            rows="2"
            autosize
            :label="$t('query.t12')"
            type="textarea"
            show-word-limit
            disabled
            @blur="setSession"
            class="query-format"
            :style="{'--formatHeight':  outputFormatHeight}"
        />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button block class="query-btn" native-type="submit">
          {{ $t('query.t13') }}
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import {Form, Field, CellGroup, Button, NavBar, Radio, RadioGroup, Picker, Popup, Toast} from 'vant';
import {request1} from "../../api/sensor";
import {getSessionItem, setSessionItem} from "../../utils/storage";
import {listDatabase} from "../../api/database";

export default {
  components: {
    [NavBar.name]: NavBar,
    [Form.name]: Form,
    [Field.name]: Field,
    [Button.name]: Button,
    [CellGroup.name]: CellGroup,
    [Radio.name]: Radio,
    [RadioGroup.name]: RadioGroup,
    [Picker.name]: Picker,
    [Popup.name]: Popup
  },

  data () {
    return {
      dbName: '',
      method: '',
      direction: '1',
      input: '',
      output: '',
      isFormat: {
        input: false,
        output: false,
      },
      showPicker: false,
      defaultIndex: 0,
      columns: [],
      inputFormatHeight: '24px',
      outputFormatHeight: '24px'
    }
  },

  created: function () {
    this.getDatabase()
    if (getSessionItem('queryData')) {
      const { dbName, method, direction, input, output, isFormat, defaultIndex} = JSON.parse(getSessionItem('queryData'))
      this.dbName = dbName
      this.method = method
      this.direction = direction
      this.input = input
      this.output = output
      this.isFormat = isFormat
      this.defaultIndex = defaultIndex
    }
  },

  methods: {
    getDatabase() {
      let self = this
      const params = {
        page: 1,
        size: 1000
      }
      listDatabase(self, params).then(response => {
        console.log(response.data)
        this.columns = response.data.rows.map(({ dbName }) => dbName) || []
      }).catch(function (error) {
        // console.log(error)
        return error
      })
    },

    onConfirm (value, index) {
      console.log(value, index)
      this.showPicker = false;
      this.defaultIndex = index
      this.dbName= value;
      this.setSession()
    },

    onFormat (target, key) {
      if (!target) return Toast(`${this.$t('query.t16')}`);
      this.isJSON(target).then(() => {
        this.isFormat[key] = !this.isFormat[key];
        if (this.isFormat[key]) {
          this[`${key}FormatHeight`] = '60vh';
          this[key] = this.JSONFormat(target);
        } else {
          this[`${key}FormatHeight`] = '24px';
          this[key] = this.JSONCompress(target);
        }
        this.setSession();
      }).catch(() => Toast(`${this.$t('query.t17')}`));
    },

    setSession () {
      const queryData = {
        dbName: this.dbName,
        method: this.method,
        direction: this.direction,
        input: this.input,
        output: this.output,
        isFormat: this.isFormat,
        defaultIndex: this.defaultIndex
      }
      setSessionItem('queryData', JSON.stringify(queryData))
    },

    onSubmit (values) {
      let self = this
      const params = {
        ...values,
        direction: values.direction === '1' ? true : false
      }
      request1(self, params).then(response => {
        console.log(response.data)
        this.output = response.data.body.output
        this.setSession()
      }).catch(function (error) {
        // console.log(error)
        return error
      })
    }
  }
};
</script>

<style lang="less">
.query {
  &-nav-bg {
    margin-bottom: 15px;
    //background: #4293F4;
    box-shadow: 0 0 25px #cac6c6;
  }

  &-btn {
    color: #fff;
    background-color: #4293F4;
    border: 1px solid #4293F4;
  }

  .query-format {
    .van-field__body {
      //height: var(--formatHeight);
    }

    .van-field__control {
      //height: 100%!important;
      white-space: pre;
    }
  }
}
</style>
